
// 学习MVC+IoC+DI
// 安装内容
// inversify reflect-metadata 用来实现依赖注入
// express 编写接口  @types/express
// 连接工具 inversify-express-utils
// orm框架 prisma
// dto class-validator + class-transformer

import 'reflect-metadata'
const { InversifyExpressServer } = require("inversify-express-utils");
const { Container } = require("inversify");
import {User} from './src/models/user/controller'
import {UserService} from './src/models/user/servers'
import express from 'express'
import {PrismaClient} from '@prisma/client'//数据库的ORM框架，准备写个注入工厂
import {PrismaDB} from './src/db/index'
import bodyParser from 'body-parser'
import { JWT } from './src/jwt';
import cors from 'cors'

var jsonParser = bodyParser.json()

const container = new Container();
/**
 * user模块
 */
container.bind(User).to(User)//注入容器
container.bind(UserService).to(UserService)

/**
 * 封装PrismaClient   提供一个注入工厂
 */
container.bind('PrismaClient').toFactory(()=>{
    return ()=>{
        return new PrismaClient()
    }
})
container.bind(PrismaDB).to(PrismaDB)

/**
 * jwt注入容器
 */
container.bind(JWT).to(JWT)

const server = new InversifyExpressServer(container);

server.setConfig((App:express.Application)=>{//配置中间件
    App.use(express.json()) //解析json格式数据
    App.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
    App.use(bodyParser.json())

    // jwt关联express
    App.use(container.get(JWT).init())
    App.use(cors())

})
const App = server.build();

App.listen(3100,()=>{
    console.log("服务启动成功");
    
});


// 扩展Express全局的User接口
declare global {
    namespace Express {
        interface User {
            id:number
            name:string
            email:string
        }
    }
}